package pl.edu.pw.stud.ltrzaska.validator;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.log4j.Logger;

import pl.edu.pw.stud.ltrzaska.logic.PolicyViolation;
import pl.edu.pw.stud.ltrzaska.logic.ValidationContext;
import pl.edu.pw.stud.ltrzaska.policy.entity.FilesystemObject;
import pl.edu.pw.stud.ltrzaska.validator.iface.IFilesystemObjectValidator;

public class ExistenceValidator implements IFilesystemObjectValidator {
	private final static Logger LOGGER = Logger.getLogger(ExistenceValidator.class);

	// TODO write specific existence validation for Group and Sequence

	@Override
	public boolean validate(FilesystemObject policyFsObj, FileObject virtualFsObj, ValidationContext vc) throws FileSystemException {

		LOGGER.debug("ExistenceValidator start walidacji istnienia dla " + policyFsObj.getRefname());

		boolean isFound = false;

		if (virtualFsObj != null) {
			FileObject[] fos = virtualFsObj.getParent().getChildren();

			for (FileObject fo : fos) {
				String n = fo.getName().getBaseName();
				if (n.equals(policyFsObj.getName())) {
					isFound = true;
					break;
				}
			}
		}
		boolean result = false;
		if (null == policyFsObj.getExistence() || "".equals(policyFsObj.getExistence())) {
			policyFsObj.setExistence(FilesystemObject.EXISTENCE_DEFAULT);
		}
		if (FilesystemObject.EXISTENCE_OBLIGATORY.equals(policyFsObj.getExistence())) {
			if (isFound) {
				result = true;
			} else {
				String shortD = "Zakazany obiekt znaleziony w systemie plikow";
				String detailD = "Zakazany obiekt znaleziony w systemie plikow";
				PolicyViolation disc = new PolicyViolation(this.getClass(), "Zakazany obiekt istnieje", shortD, detailD, policyFsObj, virtualFsObj);
				vc.reportDiscrepancy(disc);
				LOGGER.debug("Znaleziono niezgodnosc: Zakazany obiekt w znaleziony w systemie plikow: " + policyFsObj.getName());
			}
		}
		if (FilesystemObject.EXISTENCE_FORBIDDEN.equals(policyFsObj.getExistence())) {
			if (isFound) {
				result = false;
				String shortD = "Zakazany obiekt znaleziony w systemie plikow";
				String detailD = "Zakazany obiekt znaleziony w systemie plikow";
				PolicyViolation disc = new PolicyViolation(this.getClass(), "Zakazany obiekt istnieje", shortD, detailD, policyFsObj, virtualFsObj);
				vc.reportDiscrepancy(disc);

				LOGGER.debug("Znaleziono niezgodnosc: Obiekt istnieje a nie powinien: " + policyFsObj.getName());
			} else {
				result = true;
			}
		}
		if (FilesystemObject.EXISTENCE_OPTIONAL.equals(policyFsObj.getExistence())) {
			result = true;
		}

		return result;
	}

	@Override
	public boolean canValidate(FilesystemObject pfo, FileObject vfo) {
		return true; // it can validate all kinds of objects
	}
}
